package com.octopus.optiworks.dao;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.octopus.optiworks.model.Product;

@SuppressWarnings("restriction")
public class GenericStepDataDao<T extends Serializable, PK extends Serializable> extends GenericHibernateDao<T, PK>{
	
	@Resource
	private ProductDao productDao;
	
	private static Log log = LogFactory.getLog(GenericStepDataDao.class);
	
	public void synLotProperties(Long productId, Object obj, List<String> properties){
		Product product = this.productDao.get(productId);
		if(product.getLot() == null || product.getLot().length() == 0 || properties == null || properties.size() == 0)
			return;
		Field[] fields = obj.getClass().getDeclaredFields();
		StringBuffer sql = new StringBuffer("update " + obj.getClass().getSimpleName() + " set ");
		for(Field field : fields){
			if(!properties.contains(field.getName()))
				continue;
			sql.append(field.getName());
			sql.append("=");
			
			String fieldName=field.getName();   
            String stringLetter=fieldName.substring(0, 1).toUpperCase(); 
            String getName="get"+stringLetter+fieldName.substring(1); 
            try {
				Method getMethod= obj.getClass().getMethod(getName, new Class[]{});
				Object value = getMethod.invoke(obj, new Object[]{});
				if(value instanceof String){
					sql.append("'");
					sql.append(value);
					sql.append("'");
				}else if(value instanceof Long)
					sql.append(value);
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			sql.append(",");
		}
		sql.delete(sql.lastIndexOf(","), sql.length());
		sql.append(" where productId in (select id from Product where lot= :lot)");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("lot", product.getLot());
		log.debug("Syn lot properties SQL: " + sql.toString());
		super.executeSQL(sql.toString(), params);
	}
}
